package com.xnj.testweb.common.exeception;


import com.xnj.testweb.common.Result;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Iterator;

@RestControllerAdvice
public class GlobalExceptionHandler {

//    @Autowired
//    private ExceptionLogService exceptionLogService;

    // Log4j2 日志记录器
    private static final Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);

    // 处理验证异常
    @ExceptionHandler(ConstraintViolationException.class)
    public Result valiateException(ConstraintViolationException ex) {
        String info = "";

        // 获取对应的迭代器
        Iterator<ConstraintViolation<?>> iterator = ex.getConstraintViolations().iterator();
        if (iterator.hasNext()) {
            ConstraintViolation<?> next = iterator.next();
            // 获取异常信息
            info = next.getMessage();
        }
        return Result.error(info);
    }

    // 针对自定义异常，进行处理
    @ExceptionHandler(CommonException.class)
    public Result commonExeceptionHandler(CommonException e) {
        HttpServletRequest request = getCurrentRequest();
        logger.error("Exception occurred  | method: {} | URL: {} | exception: {}",
                request.getMethod(), request.getRequestURI(), e.getMsg());
        // 将捕获的异常存储到日志信息中
//        exceptionLogService.saveException(request, e.getMsg());

//        return Result.error(e.getMsg());
        return Result.error(e.getMsg(), e.getCode());
    }

    @ExceptionHandler(Exception.class)
    public Result exeptionHandler(Exception e) {
//        // 将捕获的异常存储到日志信息中
//        logger.error("系统异常: ", e);
        HttpServletRequest request = getCurrentRequest();
        logger.error("Exception occurred  | method: {} | URL: {} | exception: {}",
                request.getMethod(), request.getRequestURI(), e.getMessage(), e);
        // 将捕获的异常存储到日志信息中
//        exceptionLogService.saveException(request, e.getMessage());
//        // 当前系统中，打印日志
//        e.printStackTrace();
        return Result.error("未知异常");
    }

    /**
     * 获取当前 HTTP 请求
     */
    private HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new IllegalStateException("当前无 HTTP 请求");
        }
        return attributes.getRequest();
    }
}
